import { HttpError, WEBSOCKETS, toSuccess, useEntityManager } from "@sker/core";
import { useData } from "@sker/runtime";
import { AutoDevice } from "@sker/entities";
import { InjectionToken, container } from "tsyringe";
import { z } from "zod";


export default async () => {
    const input = z.object({
        token: z.string(),
        name: z.string(),
    })
    const body = input.parse(useData());
    await useEntityManager(async m => {
        const device = await m.findOne(AutoDevice, { where: { token: body.token } })
        if (!device) throw new HttpError(`无效token`)
        const websockets = container.resolve(WEBSOCKETS)
        const wss = websockets.get(device.device_uuid)
        if (!wss) throw new HttpError(`设备不在线`)
        const commander = getCommand(body.name);
        wss.send(JSON.stringify({
            type: CLOUD_CODE,
            payload: commander
        }))
    })

    return toSuccess(true)
}
function getCommand(name: string): ICloudCode {
    switch (name) {
        case 'OPEN_KWAI_APP':
            return {
                id: 'OPEN_KWAI_APP',
                code: `const uri = 'kwai://featured'
                const intent = app.intent({
                    action: "android.intent.action.VIEW",
                    data: uri
                });
                context.startActivity(intent);`,
                timeout: 2000,
            }
        default:
            throw new HttpError(`没有找到命令`)
    }
}
interface ICloudCode {
    id: string;
    code: string;
    timeout?: number;
}
const CLOUD_CODE: InjectionToken<ICloudCode> = `CLOUD_CODE`
